package com.lohika.vvrublevskyy.controller;

import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import com.lohika.vvrublevskyy.dao.UserDao;
import com.lohika.vvrublevskyy.model.User;

/**
 * Handles requests for the application home page.
 */
@Controller
public class UserController {

	private static final Logger logger = LoggerFactory
			.getLogger(UserController.class);

	// VIDEO: JDBC spring
	// https://www.youtube.com/watch?v=f-k823MZ02Q&list=PL_uoOKtvLq66O5xC_ckFrSjB-LPsixoGk&index=3

	/**
	 * Simply selects the home view to render by returning its name.
	 */
	
	@Autowired
	private UserDao userService;

	@RequestMapping(value="/user/create", method = RequestMethod.GET)
	public String createUser(@ModelAttribute("userAttribute") User user, Model model) {
		return "create";
	}

    @RequestMapping(value="/user", method = RequestMethod.GET)
//    @ResponseBody
    public String showAll(Model model) {
        logger.info("Showing welcome page");

        model.addAttribute("users", userService.getAll());
        return "index";
    }

	@RequestMapping(value="/user", method=RequestMethod.POST)
	public String saveUser(@ModelAttribute("userAttribute") User user, Model model) {
		userService.create(user);
		return "redirect:/user";
	}

	@RequestMapping(value="/user/update/{id}", method=RequestMethod.GET)
	public String updateUserGet(@PathVariable Long id, Model model) {
		User user = userService.read(id);
		model.addAttribute("user", user);
		return "update";
	}

	@RequestMapping(value="user/update", method=RequestMethod.POST)
    @ResponseStatus(HttpStatus.NO_CONTENT)
	public String updateUserPost(@ModelAttribute("user") User user, Model model) {
		userService.update(user);
		return "redirect:/user";
	}

	@RequestMapping(value="user/delete/{id}.htm", method=RequestMethod.GET)
	public String deleteUser(@PathVariable Long id, Model model){
		userService.delete(id);
		return "redirect:/user";
	}


	/*	@RequestMapping(value = "/", method = RequestMethod.GET)
	public String home(Locale locale, Model model) {
		logger.info("Welcome home! The client locale is {}.", locale);

		Date date = new Date();
		DateFormat dateFormat = DateFormat.getDateTimeInstance(
				DateFormat.SHORT, DateFormat.SHORT, locale);
		String formattedDate = dateFormat.format(date);

		model.addAttribute("serverTime", formattedDate);
		model.addAttribute("customAttribute", "Example Spring Application");

		return "home";
	}*/
}
